package com.dcbeida.utils;

import android.app.Activity;
import android.content.Context;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.dcbeida.MyApplication;
import com.dcbeida.listern.OnKeyListener;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by hp on 2016/7/8.
 */
public class Utils {
    /**
     * 手机按键搜索
     *
     * @param editText
     * @param listener
     */
    public static void setOnKeySearch(EditText editText, final OnKeyListener listener) {
        editText.setOnEditorActionListener(new EditText.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
           /*判断是否是手机键盘的回车键*/
                if (actionId == EditorInfo.IME_ACTION_GO || actionId == EditorInfo.IME_ACTION_SEND || actionId == EditorInfo.IME_ACTION_NEXT
                        || actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE) {
                    /*隐藏软键盘*/
                    InputMethodManager imm = (InputMethodManager) v
                            .getContext().getSystemService(
                                    Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(
                                v.getApplicationWindowToken(), 0);
                    }

                    listener.search();
                    return true;
                }
                return false;

            }
        });
    }

    public static int setDisplayMetricsHeight(Activity activity) {
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.heightPixels;
    }

    public static int setDisplayMetricsWidth(Activity activity) {
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }


    /**
     * 计算相对应的长度
     *
     * @param dip
     * @return float
     */
    public static int convertDip2Pixel(int dip) {
        final float scale = MyApplication.getInstance()
                .getApplicationContext().getResources().getDisplayMetrics().density;
        int pixel = (int) (dip * scale + 0.5f);
        return pixel;
    }

    /**
     * @param d
     * @return
     */
    public static String dFormat(double d) {
        java.text.DecimalFormat df = new java.text.DecimalFormat("0.00");
        return df.format(d);
    }

    /**
     * 获取当前时间的字符串
     *
     * @return
     */
    public static String getNowTime() {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
        String str = sDateFormat.format(curDate);
        return str;
    }

    /**
     * 获取当前时间的字符串
     *
     * @return
     */
    public static String getNowTimeYear() {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy");
        Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
        String str = sDateFormat.format(curDate);
        return str;
    }

    /**
     * 2014-05-29 12:00:00
     *
     * @param time
     * @return
     */
    public static String getformatTime(String time) {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            return sDateFormat.format(sDateFormat.parse(time));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return time;
        }
    }



    /**
     * 获取当前时间的字符串
     *
     * @return
     */
    public static String getNowTimenyrsfm() {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
        String str = sDateFormat.format(curDate);
        return str;
    }

    /**
     * 获取当前时间的前一年
     *
     * @return
     */
    public static String getNowTimeBeforeOneYear(int befourYear) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        //过去一年
        c.setTime(new Date());
        c.add(Calendar.YEAR, befourYear);
        Date y = c.getTime();
        String year = format.format(y);
        System.out.println("过去一年：" + year);
        return year;
    }

    /**
     * 获取当前时间的字符串
     *
     * @return
     */
    public static String getNowTime2() {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
        String str = sDateFormat.format(curDate);
        return str;
    }


    //阿里云上传头像objectkey
    public static String getOKey() {
        return MyApplication.user.getUid() + "/" + Constants.HEADPIC + "/" + System.currentTimeMillis();
    }


    //阿里云上传头像objectkey
    public static String getOKey2() {
        return MyApplication.user.getUid() + "/" + Constants.SHDPIC + "/" + System.currentTimeMillis();
    }

    /**
     * 提示信息
     *
     * @param aFormatMsg
     * @param aMsgArgs
     */
    public static void showTip(Context mContext, String aFormatMsg, Object... aMsgArgs) {
        String outString = String.format(aFormatMsg, aMsgArgs);
        int duration = (outString.length() > 10) ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT;
        Toast.makeText(mContext, outString, duration).show();
    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static int sp2px(Context context, float spValue) {
        final float scale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * scale + 0.5f);
    }

    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }


    public static String getDateStr2(Calendar selectedCalendar) {

        int year = selectedCalendar.get(Calendar.YEAR);
        int month = selectedCalendar.get(Calendar.MONTH);
        int day = selectedCalendar.get(Calendar.DAY_OF_MONTH);
        String dateStr = year + "-" + (month + 1) + "-" + day;
        dateStr = getYearMonthDay(dateStr);
        return dateStr;
    }

    /**
     * 2014-05-29 12:00:00
     *
     * @param time
     * @return
     */
    public static String getYearMonthDay(String time) {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            return sDateFormat.format(sDateFormat.parse(time));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return time;
        }
    }


    /**
     * 日期格式转换yyyy-MM-dd'T'HH:mm:ss.SSSXXX  (yyyy-MM-dd'T'HH:mm:ss.SSSZ) TO  yyyy-MM-dd HH:mm:ss
     *
     * @throws ParseException
     */
    public static String getYearMonthDaysf(String oldDateStr) {

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");  //yyyy-MM-dd'T'HH:mm:ss.SSSZ
        Date date = null;
        try {//此格式只有  jdk 1.7才支持  yyyy-MM-dd'T'HH:mm:ss.SSSXXX

            date = df.parse(oldDateStr);

            SimpleDateFormat df1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
            Date date1 = df1.parse(date.toString());
            DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");

            //  Date date3 =  df2.parse(date1.toString());
            return df2.format(date1);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 字符串格式时间转成long
     */
    public long Time2Long2(String attachTime) {

        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            java.util.Date date = simpleDateFormat.parse(attachTime);
            return date.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * date2比date1多的天数
     *
     * @param dateStr
     * @param dateStr2
     * @return
     */
    public static int differentDays(String dateStr, String dateStr2) {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            Date date1 = format.parse(dateStr);
            Date date2 = format.parse(dateStr2);

            Calendar cal1 = Calendar.getInstance();
            cal1.setTime(date1);

            Calendar cal2 = Calendar.getInstance();
            cal2.setTime(date2);
            int day1 = cal1.get(Calendar.DAY_OF_YEAR);
            int day2 = cal2.get(Calendar.DAY_OF_YEAR);

            int year1 = cal1.get(Calendar.YEAR);
            int year2 = cal2.get(Calendar.YEAR);
            if (year1 != year2)   //同一年
            {
                int timeDistance = 0;
                for (int i = year1; i < year2; i++) {
                    if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0)    //闰年
                    {
                        timeDistance += 366;
                    } else    //不是闰年
                    {
                        timeDistance += 365;
                    }
                }

                return timeDistance + (day2 - day1);
            } else    //不同年
            {
                System.out.println("判断day2 - day1 : " + (day2 - day1));
                return day2 - day1;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 通过时间秒毫秒数判断两个时间的间隔
     *
     * @param dateStr
     * @param dateStr2
     * @return
     */
    public static int differentDaysByMillisecond(String dateStr, String dateStr2) {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            Date date1 = format.parse(dateStr);
            Date date2 = format.parse(dateStr2);

            int days = (int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24));
            return days;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 手机号号段校验，
     * 第1位：1；
     * 第2位：{3、4、5、6、7、8}任意数字；
     * 第3—11位：0—9任意数字
     *
     * @param value
     * @return
     */
    public static boolean isTelPhoneNumber(String value) {
        if (value != null && value.length() == 11) {
            Pattern pattern = Pattern.compile("^1[3|4|5|6|7|8][0-9]\\d{8}$");
            Matcher matcher = pattern.matcher(value);
            return matcher.matches();
        }
        return false;
    }

}
